package net.xiaosaguo.mymall.search.service.impl;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import net.xiaosaguo.common.pojo.dto.es.SkuEsModel;
import net.xiaosaguo.mymall.search.config.ElasticsearchConfig;
import net.xiaosaguo.mymall.search.constant.EsConstant;
import net.xiaosaguo.mymall.search.service.ProductSaveService;
import org.elasticsearch.action.bulk.BulkItemResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * description: 商品保存
 *
 * @author xiaosaguo
 * @date 2020/06/20
 */
@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService {

    @Resource
    RestHighLevelClient client;

    @Override
    public boolean productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {
        // 将组装好的数据保存到 es 中
        // 1. 在 es 中建立索引 product 及其映射关系，这一步在 kibana 中操作

        // 2. 往 es 中保存数据
        // 2.1 构造批量操作请求
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel model : skuEsModels) {
            // 2.2 构造索引请求
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            indexRequest.id(model.getSkuId().toString());
            indexRequest.source(JSON.toJSONString(model), XContentType.JSON);
            bulkRequest.add(indexRequest);
        }
        // 2.3 执行批量请求
        // BulkRequest bulkRequest, RequestOptions options
        BulkResponse response = client.bulk(bulkRequest, ElasticsearchConfig.COMMON_OPTIONS);

        // 3. 解析响应结果
        // todo 如果出错的处理逻辑
        boolean hasFailures = response.hasFailures();
        log.info("商品上架结果：hasFailures = {}", hasFailures);
        List<String> collect = Arrays.stream(response.getItems()).map(BulkItemResponse::getId).collect(Collectors.toList());
        log.info("商品上架成功：{}", collect);
        // 这里返回方法的执行结果，给 hasFailures 取反
        return !hasFailures;
    }
}
